package com.tree.backend.interceptor;

import com.tree.backend.exception.GlobalException;
import com.tree.backend.utils.JwtUtil;
import com.tree.backend.utils.UserContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@RequiredArgsConstructor
public class JwtInterceptor implements HandlerInterceptor {

    private final JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 从请求头中获取token
        String token = request.getHeader("Authorization");

        // 检查token是否存在
        if (!StringUtils.hasText(token) || !token.startsWith("Bearer ")) {
            throw new GlobalException("未授权，请先登录");
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 请求结束后清除ThreadLocal中的用户信息，防止内存泄漏
        UserContext.clear();
    }
}